package com.gp.study.mybatis.bind;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

import com.gp.study.mybatis.session.SqlSession;

/**
 * mapper 代理类的 处理 handler
 * @author USER
 *
 */
public class MapperProxy implements InvocationHandler {
	
	private SqlSession sqlSession;
	
	public MapperProxy(SqlSession sqlSession) {
		this.sqlSession = sqlSession;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		//如何调用 sqlsession.selectOne() 根据 statementId 获取 sql
		// statementId = interfaceName.methodName
		String interfaceName = method.getDeclaringClass().getName();
		String methodName = method.getName();
		String statementId = interfaceName+"."+methodName;
		// 如果根据接口类型+方法名能找到映射的SQL，则执行SQL
        if (sqlSession.getConfiguration().hasStatement(statementId)) {
            return sqlSession.selectOne(statementId, args);
        }
        // 否则直接执行被代理对象的原方法
        return method.invoke(proxy, args);
		
	}

}
